<template>
  <a-card :bordered="false" :loading="card.loading">
    <a-form
      :form="form"
      :labelCol="{lg: {span: 7}, sm: {span: 7}}"
      :wrapperCol="{lg: {span: 10}, sm: {span: 17} }" >
      <a-form-item :label="__('上级')">
        <a-select v-if="roles.data.length > 0" name="pid" option-label-prop="label" v-decorator="[ 'pid', { initialValue: row.pid } ]" @change="onRoleSelectChange">
          <a-select-option v-for="(role) in roles.data" :key="role.id" :disabled="role.disabled" :label="role.name"> {{ role.title }} </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :label="__('名称')">
        <a-input
          v-decorator="[
              'name',
              {
                rules: [{ required: true, message: __('请输入名称') }],
                initialValue: row.name
              }
            ]"
          name="name"
          :placeholder="__('请输入名称')" />
      </a-form-item>
      <a-form-item :label="__('权限')">
        <div v-if="resourcesTree.data.length > 0">
          <a-checkbox
            :indeterminate="resourcesTree.checkedKeys.length > 0 && resourcesTree.checkedKeys.length !== resourcesTree.dataKeys.length"
            :checked="resourcesTree.checkedKeys.length === resourcesTree.dataKeys.length"
            @change="onResourcesTreeSelectAll">
            全部选中
          </a-checkbox>
          <a-checkbox
            :indeterminate="resourcesTree.expandedKeys.length > 0 && resourcesTree.expandedKeys.length !== resourcesTree.dataKeys.length"
            :checked="resourcesTree.expandedKeys.length === resourcesTree.dataKeys.length"
            @change="onResourcesTreeExpandAll">
            全部展开
          </a-checkbox>
          <a-tree
            checkable
            :selectable="false"
            @expand="onResourcesTreeExpand"
            v-model="resourcesTree.checkedKeys"
            :expanded-keys="resourcesTree.expandedKeys"
            :tree-data="resourcesTree.data"
            :replace-fields="resourcesTree.replaceFields"
            :default-checked-keys="resourcesTree.checkedKeys"
            :checked-keys="resourcesTree.checkedKeys"
          />
        </div>
        <div v-else>{{__('无')}}</div>
      </a-form-item>
      <a-form-item :label="__('状态')">
        <a-radio-group v-decorator="['status', { initialValue: row.status }]">
          <a-radio :value="1">{{ __('正常') }}</a-radio>
          <a-radio :value="0">{{ __('隐藏') }}</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item :wrapperCol="{ span: 10, offset: 7 }">
        <a-button :loading="button.loading" :disabled="button.disabled" type="primary" @click="handleSubmit">{{ __('form.basic-form.form.submit') }}</a-button>
        <a-button style="margin-left: 8px" @click="handleReset">{{ __('重置') }}</a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script>
import api from '@/api'
import treeUtils from '@/utils/tree'
import { Tree as ATree } from 'ant-design-vue'
export default {
  name: 'AdminResourceEdit',
  props: {
    dialogVm: {
      type: Object,
      default: null
    },
    id: {
      type: Number,
      default: 0
    }
  },
  components: {
    ATree
  },
  data () {
    return {
      form: this.$form.createForm(this),
      card: {
        loading: true
      },
      button: {
        loading: false,
        disabled: false
      },
      row: {},
      resourcesTree: {
        defaultExpandAll: true,
        replaceFields: {
          children: 'childlist',
          title: 'title'
        },
        apiData: {},
        data: [],
        dataKeys: [],
        checkedKeys: [],
        expandedKeys: []
      },
      roles: {
        initialValue: 0,
        data: []
      }
    }
  },
  mounted () {
    this.$on('resourceChange', (pid) => {
      this.getResources(pid)
    })
    api.admin.role.detail({
      id: this.id
    }).then((response) => {
      this.row = response.data.data.row
      this.$emit('resourceChange', this.row.pid)
      this.getRoles()
      this.card.loading = false
    })
  },
  methods: {
    getRoles () {
      api.admin.role.index({
        limit: 0
      }).then(response => {
        const rows = []
        response.data.data.rows.forEach((row) => {
          row.title = row.name
          rows.push(row)
        })
        treeUtils.init(rows)
        // 不能选择自己的ID以及子级的ID作为自己的上级
        const childrenIds = treeUtils.getChildrenIds(this.id, true)
        treeUtils.getTreeList(treeUtils.getTreeArray(0), 'title').forEach(row => {
          this.roles.data.push({ id: row.id, pid: row.pid, name: row.name, title: row.title, disabled: childrenIds.includes(row.id) })
        })
      })
    },
    getResources (pid) {
      api.admin.role.resource({
        pid: pid,
        id: this.id
      }).then(response => {
        const rows = []
        const dataKeys = []
        const selectedIds = []
        response.data.data.rows.forEach((row) => {
          if (row.type.toString() === '1') {
            row.style = 'clear: both;'
          } else {
            row.style = 'padding-top: 0;float: left;'
          }
          row.key = row.id.toString()
          rows.push(row)
          if (row.selected) {
            selectedIds.push(row.key)
          }
          dataKeys.push(row.key)
        })
        this.resourcesTree.apiData = response.data.data
        treeUtils.init(rows)
        this.resourcesTree.data = treeUtils.getTreeArray(0)
        this.resourcesTree.checkedKeys = selectedIds
        this.resourcesTree.dataKeys = dataKeys
      })
    },
    onRoleSelectChange (value) {
      this.$emit('resourceChange', value)
    },
    onResourcesTreeSelectAll (e) {
      if (e.target.checked) {
        this.resourcesTree.checkedKeys = this.resourcesTree.dataKeys
      } else {
        this.resourcesTree.checkedKeys = []
      }
    },
    onResourcesTreeExpandAll (e) {
      if (e.target.checked) {
        this.resourcesTree.expandedKeys = this.resourcesTree.dataKeys
      } else {
        this.resourcesTree.expandedKeys = []
      }
    },
    onResourcesTreeExpand (expandedKeys) {
      this.resourcesTree.expandedKeys = expandedKeys
    },
    // handler
    handleSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.button.loading = true
          this.button.disabled = true
          values.id = this.id
          values.resource_id = []
          treeUtils.init(this.resourcesTree.apiData.rows)
          this.resourcesTree.checkedKeys.forEach(resourceId => {
            // 需要获取上级的ID
            values.resource_id = values.resource_id.concat(treeUtils.getParentsIds(resourceId, true))
          })
          // 去重
          const resourceIds = {}
          values.resource_id.forEach((resourceId) => {
            resourceIds[resourceId] = resourceId
          })
          values.resource_id = Object.keys(resourceIds).join(',')
          api.admin.role.edit(values).then(response => {
            this.button.loading = false
            this.button.disabled = false
            this.dialogVm.$emit('ok') // 通知处理成功
          }).catch(() => {
            this.button.loading = false
            this.button.disabled = false
          })
        }
      })
    },
    handleReset (e) {
      e.preventDefault()
      console.log(this.form.getFieldsValue())
      this.form.resetFields()
    }
  }
}
</script>
